package cn.dduan.fool.thread.pool.executor;

import cn.dduan.fool.thread.pool.task.MyRunnable;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;

/**
 * 可指定创建线程数，并且可以重复用
 *
 * @author dduan
 * @version 1.0
 * @date 2023/3/19
 */
public class MyNewFixedThreadPool {

    /**
     * newFixedThreadPool()方法
     *
     * @param
     * @return void
     * @author dduan
     * @version 1.0
     * @date 2023/3/19
     */
    public void create() {
        // 1、使用工厂类获取线程池对象
        ExecutorService es = Executors.newFixedThreadPool(3);

        for (int i = 0; i < 10; i++) {
            // 2、提交任务
            es.submit(new MyRunnable(i));
        }
    }

    /**
     * newFixedThreadPool(ThreadFactory threadFactory)方法
     *
     * @param
     * @return void
     * @author dduan
     * @version 1.0
     * @date 2023/3/19
     */
    public void createF() {
        // 1、使用工厂类获取线程池对象
        ExecutorService es = Executors.newFixedThreadPool(3, new ThreadFactory() {
            int n = 1;

            @Override
            public Thread newThread(Runnable r) {
                return new Thread(r, String.format("newFixedThreadPool(ThreadFactory threadFactory)-%d", n++));
            }
        });

        for (int i = 0; i < 10; i++) {
            // 2、提交任务
            es.execute(new MyRunnable(i));
        }
    }

    public static void main(String[] args) {
        MyNewFixedThreadPool t = new MyNewFixedThreadPool();
        // t.create();
        t.createF();
    }
}
